// 同步诊断工具
class SyncDiagnostic {
  constructor() {
    this.diagnostics = []
    this.maxDiagnostics = 50
  }

  // 添加诊断信息
  addDiagnostic(type, message, data = null) {
    const diagnostic = {
      id: Date.now() + Math.random(),
      timestamp: new Date(),
      type,
      message,
      data
    }

    this.diagnostics.push(diagnostic)

    if (this.diagnostics.length > this.maxDiagnostics) {
      this.diagnostics.shift()
    }

    console.log(`🔍 [${type.toUpperCase()}] ${message}`, data || '')
  }

  // 诊断SignalR连接
  async diagnoseSignalRConnection(signalRService) {
    this.addDiagnostic('connection', '开始诊断SignalR连接')

    const results = {
      serviceExists: !!signalRService,
      hasConnectionMethod: !!(signalRService && signalRService.getConnectionStatus),
      isConnected: false,
      connectionId: null,
      hasRequiredMethods: false,
      messageQueueStatus: null
    }

    if (!signalRService) {
      this.addDiagnostic('error', 'SignalR服务不存在')
      return results
    }

    // 检查必要的方法
    const requiredMethods = [
      'getConnectionStatus',
      'getConnectionId',
      'sendPaintAction',
      'on',
      'off'
    ]

    const missingMethods = requiredMethods.filter(method => !signalRService[method])
    results.hasRequiredMethods = missingMethods.length === 0

    if (missingMethods.length > 0) {
      this.addDiagnostic('error', `缺少必要方法: ${missingMethods.join(', ')}`)
    } else {
      this.addDiagnostic('success', '所有必要方法都存在')
    }

    // 检查连接状态
    if (signalRService.getConnectionStatus) {
      results.isConnected = signalRService.getConnectionStatus()
      this.addDiagnostic('info', `连接状态: ${results.isConnected ? '已连接' : '未连接'}`)
    }

    // 检查连接ID
    if (signalRService.getConnectionId) {
      results.connectionId = signalRService.getConnectionId()
      this.addDiagnostic('info', `连接ID: ${results.connectionId || '无'}`)
    }

    // 检查消息队列
    if (signalRService.getMessageQueueStatus) {
      results.messageQueueStatus = signalRService.getMessageQueueStatus()
      this.addDiagnostic('info', `消息队列状态: ${JSON.stringify(results.messageQueueStatus)}`)
    }

    return results
  }

  // 诊断画布状态
  diagnoseCanvas(canvasRef) {
    this.addDiagnostic('canvas', '开始诊断画布状态')

    const results = {
      canvasExists: !!canvasRef.value,
      hasContext: false,
      contextState: null,
      dimensions: null
    }

    if (!canvasRef.value) {
      this.addDiagnostic('error', 'Canvas元素不存在')
      return results
    }

    const canvas = canvasRef.value
    results.dimensions = {
      width: canvas.width,
      height: canvas.height,
      clientWidth: canvas.clientWidth,
      clientHeight: canvas.clientHeight
    }

    this.addDiagnostic('info', `画布尺寸: ${canvas.width}x${canvas.height}`)

    const ctx = canvas.getContext('2d')
    results.hasContext = !!ctx

    if (!ctx) {
      this.addDiagnostic('error', '无法获取Canvas 2D上下文')
      return results
    }

    results.contextState = {
      fillStyle: ctx.fillStyle,
      strokeStyle: ctx.strokeStyle,
      lineWidth: ctx.lineWidth,
      lineCap: ctx.lineCap,
      lineJoin: ctx.lineJoin
    }

    this.addDiagnostic('success', 'Canvas上下文正常')
    this.addDiagnostic('info', `上下文状态: ${JSON.stringify(results.contextState)}`)

    return results
  }

  // 诊断事件监听器
  diagnoseEventListeners(signalRService, eventName = 'PaintActionReceived') {
    this.addDiagnostic('events', `开始诊断事件监听器: ${eventName}`)

    const results = {
      serviceExists: !!signalRService,
      hasOnMethod: !!(signalRService && signalRService.on),
      hasOffMethod: !!(signalRService && signalRService.off),
      listenersCount: 0
    }

    if (!signalRService) {
      this.addDiagnostic('error', 'SignalR服务不存在')
      return results
    }

    if (!signalRService.on) {
      this.addDiagnostic('error', 'SignalR服务缺少on方法')
      return results
    }

    if (!signalRService.off) {
      this.addDiagnostic('error', 'SignalR服务缺少off方法')
      return results
    }

    this.addDiagnostic('success', '事件监听器方法存在')

    // 尝试添加测试监听器来检查是否工作
    const testCallback = () => {
      this.addDiagnostic('success', '测试事件监听器被触发')
    }

    try {
      signalRService.on(eventName, testCallback)
      this.addDiagnostic('success', '测试事件监听器已添加')
      
      // 立即移除测试监听器
      signalRService.off(eventName, testCallback)
      this.addDiagnostic('success', '测试事件监听器已移除')
    } catch (error) {
      this.addDiagnostic('error', `事件监听器测试失败: ${error.message}`)
    }

    return results
  }

  // 诊断房间状态
  async diagnoseRoom(signalRService, roomId, playerId) {
    this.addDiagnostic('room', `开始诊断房间状态: ${roomId}`)

    const results = {
      roomId,
      playerId,
      canJoinRoom: false,
      joinResult: null
    }

    if (!signalRService || !signalRService.getConnectionStatus || !signalRService.getConnectionStatus()) {
      this.addDiagnostic('error', 'SignalR未连接，无法诊断房间')
      return results
    }

    if (!signalRService.joinRoom) {
      this.addDiagnostic('error', 'SignalR服务缺少joinRoom方法')
      return results
    }

    results.canJoinRoom = true

    try {
      await signalRService.joinRoom(roomId, playerId, '诊断测试玩家', '#ff0000')
      results.joinResult = 'success'
      this.addDiagnostic('success', '房间加入成功')
    } catch (error) {
      results.joinResult = 'error'
      this.addDiagnostic('error', `房间加入失败: ${error.message}`)
    }

    return results
  }

  // 诊断涂色动作发送
  async diagnosePaintAction(signalRService, roomId, playerId) {
    this.addDiagnostic('paint', '开始诊断涂色动作发送')

    const results = {
      canSend: false,
      sendResult: null,
      testData: {
        x: 100,
        y: 100,
        color: '#ff0000',
        brushSize: 10,
        tool: 'brush'
      }
    }

    if (!signalRService || !signalRService.getConnectionStatus || !signalRService.getConnectionStatus()) {
      this.addDiagnostic('error', 'SignalR未连接，无法发送涂色动作')
      return results
    }

    if (!signalRService.sendPaintAction) {
      this.addDiagnostic('error', 'SignalR服务缺少sendPaintAction方法')
      return results
    }

    results.canSend = true

    try {
      await signalRService.sendPaintAction(
        roomId,
        playerId,
        results.testData.x,
        results.testData.y,
        results.testData.color,
        results.testData.brushSize,
        results.testData.tool
      )
      results.sendResult = 'success'
      this.addDiagnostic('success', '涂色动作发送成功')
    } catch (error) {
      results.sendResult = 'error'
      this.addDiagnostic('error', `涂色动作发送失败: ${error.message}`)
    }

    return results
  }

  // 完整诊断
  async fullDiagnostic(signalRService, canvasRef, roomId, playerId) {
    this.addDiagnostic('full', '开始完整同步诊断')

    const results = {
      timestamp: new Date(),
      connection: null,
      canvas: null,
      events: null,
      room: null,
      paint: null,
      summary: {
        totalIssues: 0,
        criticalIssues: 0,
        warnings: 0
      }
    }

    // 1. 诊断连接
    results.connection = await this.diagnoseSignalRConnection(signalRService)

    // 2. 诊断画布
    results.canvas = this.diagnoseCanvas(canvasRef)

    // 3. 诊断事件监听器
    results.events = this.diagnoseEventListeners(signalRService)

    // 4. 诊断房间（如果连接正常）
    if (results.connection.isConnected) {
      results.room = await this.diagnoseRoom(signalRService, roomId, playerId)
      results.paint = await this.diagnosePaintAction(signalRService, roomId, playerId)
    }

    // 计算问题统计
    const issues = []
    
    if (!results.connection.serviceExists) issues.push('SignalR服务不存在')
    if (!results.connection.isConnected) issues.push('SignalR未连接')
    if (!results.canvas.canvasExists) issues.push('Canvas元素不存在')
    if (!results.canvas.hasContext) issues.push('Canvas上下文不可用')
    if (!results.events.hasOnMethod) issues.push('缺少事件监听器方法')

    results.summary.totalIssues = issues.length
    results.summary.criticalIssues = issues.filter(issue => 
      issue.includes('不存在') || issue.includes('未连接') || issue.includes('不可用')
    ).length
    results.summary.warnings = issues.length - results.summary.criticalIssues

    this.addDiagnostic('summary', `诊断完成: ${results.summary.totalIssues}个问题 (${results.summary.criticalIssues}个严重, ${results.summary.warnings}个警告)`)

    if (issues.length > 0) {
      this.addDiagnostic('issues', `发现的问题: ${issues.join(', ')}`)
    } else {
      this.addDiagnostic('success', '所有检查都通过，同步应该正常工作')
    }

    return results
  }

  // 获取诊断报告
  getDiagnosticReport() {
    return {
      timestamp: new Date(),
      diagnostics: [...this.diagnostics],
      summary: {
        total: this.diagnostics.length,
        byType: this.diagnostics.reduce((acc, d) => {
          acc[d.type] = (acc[d.type] || 0) + 1
          return acc
        }, {})
      }
    }
  }

  // 清空诊断记录
  clearDiagnostics() {
    this.diagnostics = []
    console.log('🔍 诊断记录已清空')
  }

  // 导出诊断报告
  exportDiagnosticReport() {
    const report = this.getDiagnosticReport()
    const blob = new Blob([JSON.stringify(report, null, 2)], { type: 'application/json' })
    const url = URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `sync-diagnostic-${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.json`
    link.click()
    URL.revokeObjectURL(url)

    this.addDiagnostic('export', '诊断报告已导出')
  }
}

// 创建全局诊断器实例
const syncDiagnostic = new SyncDiagnostic()

export default syncDiagnostic

